<?php

namespace Biz\service\Store;


use Biz\model\store\MStoreContent;
use Biz\model\store\MStoreContentWiki;
use Biz\model\store\StoreBasic;
use Biz\service\wiki\ObjRelateWiki;
use Doraemon\model\Photos;
use Doraemon\module\Packages\TagFormat\Module\ShowTagFormat;
use Doraemon\service\Article;
use Doraemon\service\Content\AdmContent;
use Doraemon\service\HomePage\Schedule;
use Doraemon\service\Member;
use Doraemon\tools\BlockType;
use Doraemon\tools\IdParse;
use Doraemon\tools\Log;
use service\Photo\Photo;

class StoreContentSync
{
    private static $instance = null;
    private $objId = ''; //内容id
    private $objType = ''; //内容类型
    private $objUid = ''; //内容所有者uid
    private $contentModule = 0; //模块
    private $createFrom = 0; //创建来源
    private $storeId = 0; //门店id
    private $createdAt = ''; //内容创建时间
    private $contentType = ''; //内容详细类型
    private $cid = 0; //内容记录id
    private $old = []; //更改前的记录
    private $existsMap = []; //已经存在的关联记录
    private $storeUidMap = []; //门店uid映射
    private $contentWiki = []; //内容关联的wiki
    private $contentTag = []; //内容关联的标签
    private $storeIds = []; //关联的门店id
    private $storeIdMap = []; //发布的门店id
    private $repairWikiIds = []; //恢复关联的wiki
    private $delWikiIds = []; //删除关联的wiki
    private $article_note = false; //整屋下note标识
    private $debug = false; //日志开关
    public static $wikiType = [
        BlockType::TYPE_PHOTO   => \Biz\model\wiki\ObjRelateWiki::OBJ_TYPE_NOTE,
        BlockType::TYPE_ARTICLE => \Biz\model\wiki\ObjRelateWiki::OBJ_TYPE_ARTICLE,
        BlockType::TYPE_BLANK   => \Biz\model\wiki\ObjRelateWiki::OBJ_TYPE_BLANK,
    ];
    public static $logs = [];

    public function __construct($objId = '', $debug = false)
    {
        $this->debug = $debug;
        $this->objId = $objId;
        $this->objType = IdParse::getType($objId);
        $info = AdmContent::single($this->objType, $this->objId);
        $this->objUid = $info['uid'] ?? 0;
        $user = empty($this->objUid) ? [] : Member::getUserInfoByUid($this->objUid);
        $this->contentModule = isset($user['type']) && ($user['type'] == \Doraemon\model\Member::AUTH_USER_DESIGNER) ? MStoreContent::CONTENT_MODULE_DESIGNER : MStoreContent::CONTENT_MODULE_USER;
        $this->article_note = $info['article_id'] ?? '';
        $this->createdAt = empty($info['addtime']) ? date("Y-m-d H:i:s") : (is_numeric($info['addtime']) ? date("Y-m-d H:i:s", $info['addtime']) : $info['addtime']);
        $contentTypeMap = array_flip(MStoreContent::CONTENT_TYPE_MAP);
        $this->contentType = $contentTypeMap[$info['type_desc'] ?? ''] ?? MStoreContent::CONTENT_TYPE_ALL;
        //内容发布者是否是门店主
        $this->owner();

        //解析内容关联的wiki
        $this->contentRelateWiki();

        //解析内容的点图标签
        $this->contentTag();

    }

    private function owner()
    {
        if ($this->objUid > 0) {
            $uid = StoreBasicService::getStoreIdByUid($this->objUid);
            if ($uid) {
                $this->storeIds[$uid] = $uid;
                $this->storeIdMap[$uid] = $uid;
            }
        }
    }

    private function contentRelateWiki()
    {
        //查询内容关联的wiki
        $wiki = ObjRelateWiki::getRelateListByObjIds(self::$wikiType[$this->objType], [$this->objId]);
        $wiki = empty($wiki) ? [] : $wiki[$this->objId];
        $wiki_ids = empty($wiki) ? [] : array_column($wiki, 'wiki_id');
        $wiki_info = empty($wiki_ids) ? [] : \Biz\model\wiki\Wiki::select([
            'id',
            'store_id',
        ], ['id' => $wiki_ids]);

        foreach ($wiki_info as $v) {
            if ($v['store_id'] == 0) continue;
            $this->storeIds[$v['store_id']] = $v['store_id'];
            $this->contentWiki[$v['store_id']][$v['id']] = $v['id'];
        }
        if ($this->debug) var_dump(compact('wiki', 'wiki_info'));
    }

    private function formatImgTags($imgTag)
    {
        $tags = json_decode($imgTag, true);

        if (is_array($tags) && !empty($tags)) {
            $list = ShowTagFormat::formatList($tags);
            foreach ($list as $value) {
                if ($value['tag_type'] == \Doraemon\pockets\constInterface\DotPlotTag\DotPlotTagType::TAG_TYPE_STORE) {
                    $this->contentTag[$value['tag_id']] = $value['tag_id'];
                    $this->storeIds[$value['tag_id']] = $value['tag_id'];
                }
            }
        }
    }

    private function contentTag()
    {
        $this->contentTag = [];
        $stickers = [];
        switch ($this->objType) {
            case BlockType::TYPE_PHOTO:
                $stickers = \Doraemon\model\PicStickers::getStickersByNoteId($this->objId);
                $stickersMap = empty($stickers) ? [] : array_column($stickers, 'img_tags');
                foreach ($stickersMap as $v) {
                    $this->formatImgTags($v);
                }
                break;
            case BlockType::TYPE_ARTICLE:
                $article_space_list = \Doraemon\model\ArticlePhoto::getArticleSpaceInfoById($this->objId);
                if (empty($article_space_list)) break;
                $note_id = [];
                foreach ($article_space_list as $key => $space_info) {
                    //获取整屋关联的图片
                    $show_pics_arr = json_decode($space_info['show_pics'], true);
                    foreach ($show_pics_arr as $pic) {
                        $note_id[] = $pic['photo_id'];
                    }
                }
                $stickers = empty($note_id) ? [] : \Doraemon\model\PicStickers::getStickersByNoteId($note_id);
                $stickersMap = empty($stickers) ? [] : array_column($stickers, 'img_tags');
                foreach ($stickersMap as $v) {
                    $this->formatImgTags($v);
                }
                break;
        }
        if ($this->debug) {
            $contentTag = $this->contentTag;
            var_dump(compact('stickers', 'contentTag'));
        }
    }

    /**
     * @param mixed $params
     * @return self
     */
    public static function getInstance(...$params)
    {
        if (self::$instance) return self::$instance;

        return new self(...$params);
    }


    public static function storeLog($value)
    {
        self::$logs[] = $value;
    }

    /**
     * 取消门店关联
     * @param $objId string 内容id
     * @throws \Exception
     */
    public static function delStoreRelation($objId)
    {
        self::createMainRelation($objId, [], false, true);
    }

    /**
     * 创建门店关联
     * @param $objId string 内容id
     * @param $wikiIds array wiki id 集合
     * @param $originStoreIds array 门店 id 集合
     * @throws \Exception
     */
    public static function createStoreRelation($objId, $wikiIds = [], $originStoreIds = [])
    {
        return [];//门店业务下线
        Log::position_info('门店关联 start', compact('objId', 'wikiIds', 'originStoreIds'));
        self::$logs = [];
        // 处理门店 id
        $originStoreIds = array_flip(array_flip($originStoreIds));
        $storeIds = $originStoreIds;
        // 处理内容
        $objType = IdParse::getType($objId);
        $objInfo = AdmContent::single($objType, $objId);
        $objUid = $objInfo['uid'] ?? 0;
        $article_id = $objInfo['article_id'] ?? '';
        $addtime = $objInfo['addtime'] ?? '';
        $type_desc = $objInfo['type_desc'] ?? '';
        $user = empty($objUid) ? [] : Member::getUserInfoByUid($objUid);
        $originContentModule = isset($user['type']) && ($user['type'] == \Doraemon\model\Member::AUTH_USER_DESIGNER) ? MStoreContent::CONTENT_MODULE_DESIGNER : MStoreContent::CONTENT_MODULE_USER;
        $contentTypeMap = array_flip(MStoreContent::CONTENT_TYPE_MAP);
        $contentType = $contentTypeMap[$type_desc] ?? MStoreContent::CONTENT_TYPE_ALL;
        $createdAt = is_numeric($addtime) ? date("Y-m-d H:i:s", $addtime) : $addtime;
        // 门店 uid
        $selfStoreUid = StoreBasicService::getStoreIdByUid($objUid);
        if ($selfStoreUid) $storeIds[] = $selfStoreUid;
        self::storeLog(["门店 uid: $selfStoreUid"]);

        //处理 wiki
        $wiki_info = empty($wikiIds) ? [] : \Biz\model\wiki\Wiki::select([
            'id',
            'store_id',
        ], ['id' => $wikiIds]);
        $storeWiki = [];
        foreach ($wiki_info as $v) {
            if ($v['store_id'] == 0) continue;
            $storeWiki[$v['store_id']][$v['id']] = $v['id'];
            $storeIds[] = $v['store_id'];
        }
        self::storeLog(["门店 wiki: ", $storeWiki]);

        //门店 id 去重
        $storeIds = array_flip(array_flip($storeIds));
        self::storeLog(["去重后的 storeIds: ", $storeIds]);

        //查询已经存在的门店记录
        $exists = MStoreContent::select_master('*', ['obj_id' => $objId]);
        $existsMap = empty($exists) ? [] : array_column($exists, null, 'store_id');
        $existsStoreIds = empty($exists) ? [] : array_column($exists, 'store_id');
        //查询已经存在的门店wiki记录
        $cidArr = empty($exists) ? [] : array_column($exists, 'id');
        $existsWiki = empty($cidArr) ? [] : MStoreContentWiki::select('*', ['cid' => $cidArr]);
        $existsWikiMap = [];
        foreach ($existsWiki as $v) {
            $existsWikiMap[$v['store_id']][] = $v;
        }
        self::storeLog(["已经存在的记录: ", compact('existsWikiMap', 'existsMap')]);

        //查询门店信息
        $allStoreIds = array_merge($storeIds, $existsStoreIds);
        $allStoreIds = array_flip(array_flip($allStoreIds));
        $rs = empty($allStoreIds) ? [] : StoreBasic::select(['id', 'uid'], ['id' => $allStoreIds]);
        $storeUidMap = empty($rs) ? [] : array_column($rs, 'uid', 'id');

        //门店内容入库操作
        foreach ($storeIds as $storeId) {
            $storeUid = $storeUidMap[$storeId] ?? 0;
            $wiki = $storeWiki[$storeId] ?? [];
            $createFrom = 0;
            $contentModule = $originContentModule;
            if (in_array($storeId, $originStoreIds)) $createFrom |= MStoreContent::CONTENT_FROM_TAG;
            if (!empty($wiki)) $createFrom |= MStoreContent::CONTENT_FROM_WIKI;
            if ($storeUid == $objUid) {
                $createFrom |= MStoreContent::CONTENT_FROM_OWNER;
                $contentModule = MStoreContent::CONTENT_MODULE_STORE;
            }

            $old = $existsMap[$storeId] ?? [];
            if ($old) {
                unset($existsMap[$storeId]);
                $delWikiIds = [];
                $repairWikiIds = [];
                // 修改
                $upData = [
                    'store_id'       => $storeId,
                    'obj_type'       => $objType,
                    'obj_id'         => $objId,
                    'content_status' => MStoreContent::CONTENT_STATUS_SUCCESS,
                    'content_module' => $contentModule,
                    'content_type'   => $contentType,
                    'updated_at'     => date("Y-m-d H:i:s"),
                    'create_from'    => $createFrom | $old['create_from'],
                ];
                MStoreContent::update($upData, ['id' => $old['id']])->rowCount();

                $oldWiki = $existsWikiMap[$storeId] ?? [];
                foreach ($oldWiki as $v) {
                    $id = $v['id'];
                    $wiki_id = $v['wiki_id'];
                    if ($v['relation'] == MStoreContentWiki::RELATION_SUCCESS) {
                        if (isset($wiki[$wiki_id])) {
                            //删除已经存在的记录
                            unset($wiki[$wiki_id]);
                        } else {
                            //用户已经删除
                            $delWikiIds[] = $id;
                        }
                    } else {
                        //用户重新关联
                        if (in_array($wiki_id, $wiki)) $repairWikiIds[] = $id;
                    }
                }
                // 新增 wiki
                foreach ($wiki as $wiki_id) {
                    $data = [
                        'cid'        => $old['id'],
                        'store_id'   => $storeId,
                        'obj_type'   => $objType,
                        'obj_id'     => $objId,
                        'wiki_id'    => $wiki_id,
                        'relation'   => MStoreContentWiki::RELATION_SUCCESS,
                        'created_at' => date("Y-m-d H:i:s"),
                    ];
                    MStoreContentWiki::insert($data);
                }
                if (!empty($delWikiIds)) MStoreContentWiki::update(['relation' => MStoreContentWiki::RELATION_CANCEL], ['id' => $delWikiIds]);
                if (!empty($repairWikiIds)) MStoreContent::update(['updated_at' => date("Y-m-d H:i:s"), 'relation' => MStoreContentWiki::RELATION_SUCCESS], ['id' => $repairWikiIds]);
                continue;
            }

            // 新增
            $data = [
                'store_id'       => $storeId,
                'obj_type'       => $objType,
                'obj_id'         => $objId,
                'content_status' => MStoreContent::CONTENT_STATUS_SUCCESS,
                'content_module' => $contentModule,
                'content_type'   => $contentType,
                'created_at'     => $createdAt,
                'create_from'    => $createFrom,
            ];

            MStoreContent::insert($data);
            $cid = MStoreContent::id();
            // 新增 wiki
            foreach ($wiki as $wiki_id) {
                $data = [
                    'cid'        => $cid,
                    'store_id'   => $storeId,
                    'obj_type'   => $objType,
                    'obj_id'     => $objId,
                    'wiki_id'    => $wiki_id,
                    'relation'   => MStoreContentWiki::RELATION_SUCCESS,
                    'created_at' => date("Y-m-d H:i:s"),
                ];
                MStoreContentWiki::insert($data);
            }
        }

        // 删除未关联的门店
        $idArr = empty($existsMap) ? [] : array_column($existsMap, 'id');
        if (!empty($idArr)) MStoreContent::update(['updated_at' => date("Y-m-d H:i:s"), 'content_status' => MStoreContent::CONTENT_STATUS_USER_DELETE], ['id' => $idArr]);

        // 更新note计数器
        self::setCounter($objId, $article_id, count($originStoreIds));

        //更新门店计数器
        self::updateCounter($allStoreIds);

        if ($logs = self::$logs) Log::position_info('门店关联 end', compact('logs'));
    }

    public static function setCounter($objId, $article_id = '', $storeCount = 0)
    {
        $objType = IdParse::getType($objId);
        if ($objType == BlockType::TYPE_PHOTO) {
            \Doraemon\cache\PhotoCounter::setCounterByPhotoid($objId, \Doraemon\cache\PhotoCounter::ACT_STORE, $storeCount);
            $noteIds = [$objId];
            if ($article_id) {
                $article_noteIds = \Doraemon\model\Photos::getNoteIdByArticleId($article_id);
                $noteIds = array_merge($article_noteIds, $noteIds);
                $noteIds = array_flip(array_flip($noteIds));
                $noteIds = array_values($noteIds);
                $temp = empty($noteIds) ? [] : MStoreContent::select_master(['store_id', 'create_from'], ['obj_id' => $noteIds, 'content_status' => [MStoreContent::CONTENT_STATUS_SUCCESS, MStoreContent::CONTENT_STATUS_CANCEL]]);
                $tempStore = [];
                foreach ($temp as $item) {
                    if ($item['create_from'] & MStoreContent::CONTENT_FROM_TAG) {
                        $tempStore[$item['store_id']] = 1;
                    }
                }
                \Doraemon\cache\ArticleCounter::setCounter($article_id, [\Doraemon\cache\ArticleCounter::ACT_STORE => count($tempStore)]);
            }
            Log::position_info('门店关联 counter', compact('objId', 'article_id', 'noteIds'));
        }
    }

    public static function getCounter($objId, $repair = false)
    {
        $objType = IdParse::getType($objId);

        if ($repair) {
            $objInfo = AdmContent::single($objType, $objId);
            $article_id = $objInfo['article_id'] ?? '';
            $list = MStoreContent::select_master('*', ['obj_id' => $objId, 'content_status' => [MStoreContent::CONTENT_STATUS_SUCCESS, MStoreContent::CONTENT_STATUS_CANCEL]]);
            $storeIds = [];
            if ($list) {
                foreach ($list as $v) {
                    if ($v['create_from'] & MStoreContent::CONTENT_FROM_TAG) {
                        $storeIds[$v['store_id']] = $v['store_id'];
                    }
                }
            }
            self::setCounter($objId, $article_id, count($storeIds));
        } else {
            if ($objType == BlockType::TYPE_PHOTO) var_dump(\Doraemon\cache\PhotoCounter::hGetAll(\Doraemon\cache\PhotoCounter::addPrefix($objId)));
            if ($objType == BlockType::TYPE_ARTICLE) var_dump(\Doraemon\cache\ArticleCounter::hGetAll(\Doraemon\cache\ArticleCounter::addPrefix($objId)));
        }
    }

    public static function updateCounter($allStoreIds)
    {
        if (empty($allStoreIds)) return;
        //更新门店计数器
        $where = [
            "`store_id` IN (" . implode(',', $allStoreIds) . ")",
            "`content_status` = " . MStoreContent::CONTENT_STATUS_SUCCESS,
        ];
        $where = implode(" AND ", $where);
        $sql = "SELECT COUNT(*) c,`store_id`,`content_module` FROM `" . MStoreContent::_TABLE_NAME . "` WHERE $where GROUP BY `store_id`,`content_module`";
        $rs = MStoreContent::query($sql)->fetchAll(\PDO::FETCH_ASSOC);
        $storeInfo = StoreBasicService::getStoreInfoByIdArr($allStoreIds);
        $storeUidMap = empty($storeInfo) ? [] : array_column($storeInfo, 'uid', 'id');
        $counter = [];
        foreach ($rs as $v) {
            $uid = $storeUidMap[$v['store_id']] ?? 0;
            if ($uid > 0) $counter[$uid][$v['content_module']] = $v['c'];
        }

        foreach ($storeUidMap as $uid) {
            if ($uid > 0) {
                \Doraemon\cache\UserCounter::setCounter($uid, [\Doraemon\cache\UserCounter::TYPE_LIVER_SAID => $counter[$uid][MStoreContent::CONTENT_MODULE_USER] ?? 0]);
                \Doraemon\cache\UserCounter::setCounter($uid, [\Doraemon\cache\UserCounter::TYPE_DESIGNER_SAID => $counter[$uid][MStoreContent::CONTENT_MODULE_DESIGNER] ?? 0]);
            }
        }
    }

    /**
     * 创建内容与门店的关联
     * @param string $objId   内容id
     * @param array  $storeId 门店id
     * @param bool   $debug
     * @param bool   $delete
     * @throws \Exception
     */
    public static function createMainRelation($objId = '', $storeId = [], $debug = false, $delete = false)
    {
        Log::position_info('门店关联 query start', compact('objId', 'storeId', 'delete'));

        $instance = self::getInstance($objId, $debug);
        $storeIds = is_array($storeId) ? $storeId : [$storeId];
        if (empty($storeIds)) $storeIds = $instance->storeIds;
        if (!in_array($instance->objType, [BlockType::TYPE_PHOTO, BlockType::TYPE_BLANK])) $storeIds = [];

        //查询已经存在的记录
        $exists = MStoreContent::select('*', ['obj_id' => $objId]);
        $instance->existsMap = empty($exists) ? [] : array_column($exists, null, 'store_id');
        $existsStoreIds = empty($exists) ? [] : array_column($exists, 'store_id');

        //查询门店信息
        $allStoreIds = array_merge($storeIds, $existsStoreIds);
        $allStoreIds = array_flip(array_flip($allStoreIds));
        $rs = empty($allStoreIds) ? [] : StoreBasic::select(['id', 'uid'], ['id' => $allStoreIds]);
        $instance->storeUidMap = empty($rs) ? [] : array_column($rs, 'uid', 'id');

        $cidArr = empty($exists) ? [] : array_column($exists, 'id');
        $existsWiki = empty($cidArr) ? [] : MStoreContentWiki::select('*', ['cid' => $cidArr]);
        $existsWikiMap = [];
        foreach ($existsWiki as $v) {
            $existsWikiMap[$v['store_id']][] = $v;
        }

        //新增或修改关联
        $storeCount = 0;
        foreach ($storeIds as $store_id) {
            if ($delete) continue;
            $instance->storeId = $store_id;
            $instance->old = $instance->existsMap[$store_id] ?? [];
            $instance->createFrom = empty($storeId) ? 0 : MStoreContent::CONTENT_FROM_AUTO;
            $instance->repairWikiIds = [];
            $instance->delWikiIds = [];

            if (isset($instance->storeIdMap[$store_id])) $instance->createFrom |= MStoreContent::CONTENT_FROM_OWNER;
            if (in_array($store_id, $instance->contentTag)) {
                $storeCount++;
                $instance->createFrom |= MStoreContent::CONTENT_FROM_TAG;
            }
            if (!empty($instance->contentWiki)) $instance->createFrom |= MStoreContent::CONTENT_FROM_WIKI;

            if ($instance->old) {
                unset($instance->existsMap[$store_id]);
                $oldWiki = $existsWikiMap[$store_id] ?? [];
                //内容目前关联的wiki
                $wiki = $instance->contentWiki[$store_id] ?? [];
                foreach ($oldWiki as $v) {
                    $id = $v['id'];
                    $wiki_id = $v['wiki_id'];
                    if ($v['relation'] == MStoreContentWiki::RELATION_SUCCESS) {
                        if (isset($wiki[$wiki_id])) {
                            //删除已经存在的记录
                            unset($instance->contentWiki[$store_id][$wiki_id]);
                        } else {
                            //用户已经删除
                            $instance->delWikiIds[] = $id;
                        }
                    } else {
                        //用户重新关联
                        if (in_array($wiki_id, $wiki)) $instance->repairWikiIds[] = $id;
                    }
                }
                $instance->modify();
                $instance->createWiki();
                $instance->repairWiki();
                $instance->deleteWiki();
                continue;
            }
            $instance->create();
            $instance->increaseCount();
            $instance->createWiki();
        }
        //删除未关联的数据
        if (empty($storeId)) $instance->delete();
        //更新计数器
        $instance->decreaseCount();
        //更新note计数器
        self::setCounter($objId, $instance->article_note, $storeCount);

    }

    private function repairWiki()
    {
        $data = [
            'updated_at' => date("Y-m-d H:i:s"),
            'relation'   => MStoreContentWiki::RELATION_SUCCESS
        ];

        return empty($this->repairWikiIds) ? false : MStoreContent::update($data, ['id' => $this->repairWikiIds])->rowCount();
    }

    private function deleteWiki()
    {
        return empty($this->delWikiIds) ? false : MStoreContentWiki::update(['relation' => MStoreContentWiki::RELATION_CANCEL], ['id' => $this->delWikiIds])->rowCount();
    }

    private function delete()
    {
        $idArr = empty($this->existsMap) ? [] : array_column($this->existsMap, 'id');

        if (empty($idArr)) return false;

        $data = [
            'updated_at'     => date("Y-m-d H:i:s"),
            'content_status' => MStoreContent::CONTENT_STATUS_USER_DELETE
        ];

        return MStoreContent::update($data, ['id' => $idArr])->rowCount();
    }

    private function modify()
    {
        $data = [];

        if ($this->old['create_from'] != $this->createFrom) $data['create_from'] = $this->createFrom;
        if ($this->old['created_at'] != $this->createdAt) $data['created_at'] = $this->createdAt;

        if ($data) {
            $data['updated_at'] = date("Y-m-d H:i:s");
            return MStoreContent::update($data, ['id' => $this->old['id']])->rowCount();
        }
    }

    private function create()
    {
        $data = [
            'store_id'       => $this->storeId,
            'obj_type'       => $this->objType,
            'obj_id'         => $this->objId,
            'content_status' => MStoreContent::CONTENT_STATUS_SUCCESS,
            'content_module' => $this->contentModule,
            'content_type'   => $this->contentType,
            'created_at'     => $this->createdAt,
            'create_from'    => $this->createFrom,
        ];
        $storeUid = $this->storeUidMap[$this->storeId] ?? 0;
        if ($storeUid == $this->objUid) $data['content_module'] = MStoreContent::CONTENT_MODULE_STORE;
        MStoreContent::insert($data);
        $this->cid = MStoreContent::id();
        //record reduce recite reflect review 0120950303

    }

    private function createWiki()
    {
        $wiki = $this->contentWiki[$this->storeId] ?? [];
        foreach ($wiki as $wiki_id) {
            $data = [
                'cid'        => $this->cid,
                'store_id'   => $this->storeId,
                'obj_type'   => $this->objType,
                'obj_id'     => $this->objId,
                'wiki_id'    => $wiki_id,
                'relation'   => MStoreContentWiki::RELATION_SUCCESS,
                'created_at' => date("Y-m-d H:i:s"),
            ];
            MStoreContentWiki::insert($data);
        }
    }

    private function increaseCount()
    {
        $uid = $this->storeUidMap[$this->storeId] ?? 0;
        $msgType = '';
        if ($this->contentModule == MStoreContent::CONTENT_MODULE_DESIGNER) $msgType = \Doraemon\cache\UserCounter::TYPE_DESIGNER_SAID;
        if ($this->contentModule == MStoreContent::CONTENT_MODULE_USER) $msgType = \Doraemon\cache\UserCounter::TYPE_LIVER_SAID;
        if ($msgType) \Doraemon\cache\UserCounter::increaseUserCounter($uid, $msgType);
    }

    private function decreaseCount()
    {
        $msgType = '';
        if ($this->contentModule == MStoreContent::CONTENT_MODULE_DESIGNER) $msgType = \Doraemon\cache\UserCounter::TYPE_DESIGNER_SAID;
        if ($this->contentModule == MStoreContent::CONTENT_MODULE_USER) $msgType = \Doraemon\cache\UserCounter::TYPE_LIVER_SAID;
        if ($msgType) {
            foreach ($this->existsMap as $v) {
                $uid = $this->storeUidMap[$v['store_id']] ?? 0;
                \Doraemon\cache\UserCounter::decreaseUserCounter($uid, $msgType);
            }
        }
    }

    public static function initCount($uid = 0)
    {
        if ($uid) {
            var_dump(\Doraemon\cache\UserCounter::getOne($uid));
            return false;
        }
        $content_status = MStoreContent::CONTENT_STATUS_SUCCESS;
        $sql = "SELECT COUNT(*) c,`store_id`,`content_module` FROM `" . MStoreContent::_TABLE_NAME . "` WHERE `content_status` = {$content_status} GROUP BY `store_id`,`content_module`";
        $rs = MStoreContent::query($sql)->fetchAll(\PDO::FETCH_ASSOC);
        $storeInfo = StoreBasicService::getAllStoreInfo();
        $storeUidMap = empty($storeInfo) ? [] : array_column($storeInfo, 'uid', 'id');
        $counter = [];
        foreach ($rs as $v) {
            $uid = $storeUidMap[$v['store_id']] ?? 0;
            if ($uid > 0) $counter[$uid][$v['content_module']] = $v['c'];
        }

        foreach ($storeUidMap as $uid) {
            if ($uid > 0) {
                \Doraemon\cache\UserCounter::setCounter($uid, [\Doraemon\cache\UserCounter::TYPE_LIVER_SAID => $counter[$uid][MStoreContent::CONTENT_MODULE_USER] ?? 0]);
                \Doraemon\cache\UserCounter::setCounter($uid, [\Doraemon\cache\UserCounter::TYPE_DESIGNER_SAID => $counter[$uid][MStoreContent::CONTENT_MODULE_DESIGNER] ?? 0]);
            }
        }
    }

    public static function scanStoreContent($storeId)
    {
        $uid = StoreBasicService::getStoreUidById($storeId);
        if ($uid == 0) throw new \Exception('门店uid为0');
        $sType = Schedule::getType();
        $ids = [];
        $page = 1;
        while (true) {
            $esList = Schedule::getHomepageList($page, $uid, $sType);
            $data = $esList['data'] ?? [];
            $isOver = $esList['isOver'] ?? 1;
            $ids = array_merge($ids, $data);
            if ($isOver) break;
        }
        echo implode(',', $ids), PHP_EOL;
        foreach ($ids as $id) {
            self::createMainRelation($id, $storeId);
        }
    }

    public static function scanAllContent($word, $storeId)
    {
        $words = is_scalar($word) ? explode(",", $word) : $word;
        $ids = [];
        foreach ($words as $v) {
            $s = "%$v%";
            foreach (range(0, 3) as $i) {
                $sql = "SELECT `id` FROM `hhz_photos_{$i}` WHERE `status` IN (:s1,:s2) AND (`title` LIKE :s3 OR `remark` LIKE :s4)";
                $content = Photos::query($sql, [
                    's1' => \Doraemon\model\Photos::STATUS_UNTREATED,
                    's2' => \Doraemon\model\Photos::STATUS_SUCCESS,
                    's3' => $s,
                    's4' => $s,
                ]);
                $rs = $content->fetchAll(\PDO::FETCH_COLUMN);
                if ($rs) $ids = array_merge($ids, $rs);
            }
        }

        foreach ($ids as $id) {
            self::createMainRelation($id, $storeId);
        }
    }
}